<template>
  <div class="progress-middle-axis">
    <div class="u-values">
      <span v-for="item in config" :style="{ color: item.color }">
        {{ item.valueText }}
      </span>
    </div>
    <div class="u-bar" ref="barRef" :style="{ background: linearGradient }">
      <div
        class="u-slider"
        :style="{ width: sliderWidth, left: sliderLeft }"
      ></div>
      <div class="u-circles">
        <div
          class="u-circle"
          v-for="(item, index) in config"
          :style="getCircleStyle(item, index)"
        ></div>
      </div>
    </div>
    <div class="u-labels">
      <div
        class="u-label"
        v-for="item in config"
        :style="{ color: item.color }"
      >
        {{ item.label }}
      </div>
    </div>
  </div>
</template>

<script setup name="ProgressMiddleAxis">
import { ref, computed } from 'vue'

const props = defineProps({
  config: Array, // [{label, color }]，目前只支持3个子项
  value: [Number, null], // 传入80表示80%
})

const barRef = ref()

// 根据config获取线性渐变
const linearGradient = computed(() => {
  let arr = []
  arr = props?.config?.map((item) => item.color)
  return `linear-gradient(270deg,${arr.reverse().join(',')})`
})

// 数值接近50的话则为true，slider会有一个14px的最小宽度
const isTooSmall = computed(() => {
  return (barRef?.value?.offsetWidth * Math.abs(props?.value - 50)) / 100 < 14
})

// 滑块的宽度
const sliderWidth = computed(() => {
  if (props?.value !== null) {
    const diff = Math.abs(props.value - 50)
    return isTooSmall.value ? '14px' : `calc(${diff}% + 7px)`
  } else {
    return '0px'
  }
})

// 滑块的左位移
const sliderLeft = computed(() => {
  const value = props?.value ?? 50
  if (isTooSmall.value) {
    return `calc(${50}% - 7px)`
  } else {
    return value <= 50 ? `calc(${value}%)` : `calc(${50}% - 7px)`
  }
})

function getCircleStyle(cfg, index) {
  const value = props?.value
  let backgroundColor = cfg.color
  if (
    (value === 0 && index === 0) ||
    (value && index === 1) ||
    (value === 100 && index === 2)
  )
    backgroundColor = '#fff'
  return {
    backgroundColor,
  }
}
</script>

<style lang="stylus" scoped>
.progress-middle-axis
  .u-values,.u-labels
    display flex
    justify-content space-between
    line-height 28px
    font-size 14px
  .u-bar
    position relative
    width: 100%;
    height: 14px;
    border-radius: 14px;
    overflow hidden
    .u-slider
      position absolute
      height 100%
      border-radius 14px
      box-shadow 0 0 0 2000px #f5f8fc
    .u-circle
      position absolute
      top 4px
      width 6px
      height 6px
      border-radius 6px
      background #fff
      &:nth-child(1)
        left 10px
      &:nth-child(2)
        left 50%
        margin-left -3px
      &:nth-child(3)
        right 10px
</style>
